package com.program.facesigninsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.program.facesigninsystem.iteration.dto.SignInActivityByTemplate;
import com.program.facesigninsystem.iteration.dto.SignInTemplateInfo;
import com.program.facesigninsystem.iteration.dto.SigninactivityInfo;
import com.program.facesigninsystem.iteration.dto.TemplateInfoAmend;
import com.program.facesigninsystem.iteration.entity.*;
import com.program.facesigninsystem.iteration.mapper.*;
import com.program.facesigninsystem.service.IRewardService;
import com.program.facesigninsystem.service.SignInTemplateService;
import com.program.facesigninsystem.util.GetInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Slf4j
@Service
public class SignInTemplateServiceImpl implements SignInTemplateService {

    @Resource
    SignintemplateMapper signintemplateMapper;
    @Resource
    TemplateActivityLinkMapper templateActivityLinkMapper;
    @Resource
    SigninactivityMapper signinactivityMapper;
    @Resource
    SigninlinkMapper signinlinkMapper;
    @Resource
    RewardPointsMapper rewardPointsMapper;
    @Resource
    IRewardService iRewardService;
    @Resource
    SigninclassMapper signinclassMapper;
    @Resource
    RedisTemplate redisTemplate;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;


    @Override
    public List<SignInTemplateInfo> getTemplateList(String uid) {


        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            List<SignintemplateEntity> signintemplateEntityList = signintemplateMapper.selectList(new QueryWrapper<SignintemplateEntity>().eq("tid", uid));
            List<SignInTemplateInfo> signInTemplateInfoList = new ArrayList<>();

            for (SignintemplateEntity signintemplateEntity : signintemplateEntityList) {

                SignInTemplateInfo signInTemplateInfo = new SignInTemplateInfo();
                signInTemplateInfo.setId(signintemplateEntity.getId())
                        .setName(signintemplateEntity.getName());
                signInTemplateInfoList.add(signInTemplateInfo);
            }
            //提交事务
            platformTransactionManager.commit(status);

            return signInTemplateInfoList;
        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return null;
        }
    }

    @Override
    public SignintemplateEntity getTemplateDetail(int templateId) {

        return signintemplateMapper.selectById(templateId);
    }

    @Override
    public Integer addTemplate(SignintemplateEntity signintemplateEntity) {

        return signintemplateMapper.insert(signintemplateEntity);
    }

    @Override
    public Integer delTemplate(int templateId) {

        return signintemplateMapper.deleteById(templateId);
    }

    @Override
    public Integer updateTemplate(SignintemplateEntity signintemplateEntity) {

        return signintemplateMapper.updateById(signintemplateEntity);
    }

    @Override
    public List<SignInActivityByTemplate> getActivityListByTemplateId(int templateId) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);

        List<SignInActivityByTemplate> signInActivityByTemplateList = new ArrayList<>();
        try {

            List<TemplateActivityLinkEntity> templateActivityLinkEntityList = templateActivityLinkMapper.selectList(new QueryWrapper<TemplateActivityLinkEntity>().eq("template_id", templateId));
            for (TemplateActivityLinkEntity templateActivityLinkEntity : templateActivityLinkEntityList) {

                SignInActivityByTemplate signInActivityByTemplate = new SignInActivityByTemplate();
                //查询签到活动
                SigninactivityEntity signinactivityEntity = signinactivityMapper.selectOne(new QueryWrapper<SigninactivityEntity>().eq("actid", templateActivityLinkEntity.getActivityId()));
                SigninactivityInfo signinactivityInfo = new SigninactivityInfo();
                if (!signinactivityEntity.getCid().equals("") && signinactivityEntity.getCid() != null)
                    signinactivityInfo.setCName(signinclassMapper.selectById(Integer.valueOf(signinactivityEntity.getCid())).getName());
                signinactivityInfo.setActid(signinactivityEntity.getActid())
                        .setTitle(signinactivityEntity.getTitle())
                        .setCreatetime(signinactivityEntity.getCreatetime())
                        .setCaption(signinactivityEntity.getCaption())
                        .setActtype(signinactivityEntity.getActtype())
                        .setSignStopType(signinactivityEntity.getSignStopType())
                        .setCid(signinactivityEntity.getCid())
                        .setTid(signinactivityEntity.getTid());
                signInActivityByTemplate.setSigninactivityInfo(signinactivityInfo);

                //查询此签到活动下的所有衍生签到（link）
                List<SigninlinkEntity> signinlinkEntityList = signinlinkMapper.selectList(new QueryWrapper<SigninlinkEntity>().eq("actid", signinactivityEntity.getActid()));
                signInActivityByTemplate.setSigninlinkEntityList(signinlinkEntityList);

                signInActivityByTemplateList.add(signInActivityByTemplate);
            }

            //提交事务
            platformTransactionManager.commit(status);
            return signInActivityByTemplateList;
        } catch (Exception e) {

            //回滚事务
            e.printStackTrace();
            platformTransactionManager.rollback(status);
            return null;
        }
    }

    @Override
    public Integer createActivity(int templateId) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        int code = 1;
        try {
            SignintemplateEntity signintemplateEntity = signintemplateMapper.selectById(templateId);

            String actId = GetInfoUtil.getId();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = dateFormat.format(System.currentTimeMillis());

            //创建签到活动
            SigninactivityEntity signinactivityEntity = new SigninactivityEntity();
            signinactivityEntity.setActid(actId)
                    .setTitle(signintemplateEntity.getTitle())
                    .setCreatetime(currentTime)
                    .setCaption(signintemplateEntity.getCaption())
                    .setActtype(signintemplateEntity.getActType())
                    .setSignStopType(signintemplateEntity.getSignStopType())
                    .setCid(signintemplateEntity.getCid())
                    .setTid(signintemplateEntity.getTid());
            signinactivityMapper.insert(signinactivityEntity);

            //创建此签到活动下的所有衍生签到（link）
            String[] types = signintemplateEntity.getLinkType().split(",");
            String[] times = signintemplateEntity.getTimes().split(",");
            String[] durations = signintemplateEntity.getDuration().split(",");
            String[] locations = signintemplateEntity.getWhetherLocation().split(",");

            for (int i = 0; i < types.length; i++) {
                for (int j = 0; j < Integer.parseInt(times[i]); j++) {

                    SigninlinkEntity signinlinkEntity = new SigninlinkEntity();
                    signinlinkEntity.setLid(GetInfoUtil.getId())
                            .setLinktype(Integer.parseInt(types[i]))
//                            .setStarttime()
//                            .setEndtime()
                            .setDuration(durations[i])
                            .setStatus(0)
                            .setActid(signinactivityEntity.getActid());
                    if (Integer.parseInt(locations[i]) == 0)
                        signinlinkEntity.setLocationX(0.0)
                                .setLocationY(0.0)
                                .setRangement(0.0);
                    signinlinkMapper.insert(signinlinkEntity);
                }
            }

            //模板使用次数+1
            if (signintemplateEntity.getUseNum() == null)
                signintemplateEntity.setUseNum(1);
            else
                signintemplateEntity.setUseNum(signintemplateEntity.getUseNum() + 1);
            signintemplateMapper.updateById(signintemplateEntity);

            //创建关联
            TemplateActivityLinkEntity templateActivityLinkEntity = new TemplateActivityLinkEntity();
            templateActivityLinkEntity.setActivityId(actId)
                    .setTemplateId(templateId);
            templateActivityLinkMapper.insert(templateActivityLinkEntity);

            //判定积分情况
            final int rewardPerTime = 30;
            final int dayMaxReward = 100;
            RewardPointsEntity rewardPointsEntity = rewardPointsMapper.selectOne(new QueryWrapper<RewardPointsEntity>().eq("uid", signintemplateEntity.getTid()));
            String lastGainDay;
            String currentDay = dateFormat.format(System.currentTimeMillis()).substring(0, 10);
            //先判断列表是否有记录，没有则新增记录

            if (rewardPointsEntity == null) {
                iRewardService.addNewRewards(signintemplateEntity.getTid(), 0, 0, 0, 1,
                        currentDay, rewardPerTime, rewardPerTime);
            } else {
                //有则更新记录
                int limitFromRecordA = rewardPointsEntity.getLimitFromRecordA();
                int limitFromRecordB = rewardPointsEntity.getLimitFromRecordB();
                int limitFromRecordC = rewardPointsEntity.getLimitFromRecordC();
                int limitFromRecordActivity = rewardPointsEntity.getLimitFromActivity();
                lastGainDay = rewardPointsEntity.getLastGainDay();
                int rewardPoints = rewardPointsEntity.getRewardPoints();
                log.info("lastGainDay:" + lastGainDay);

                if (!lastGainDay.equals(currentDay)) {
                    //如果上次获取积分的日期不等于今天，则直接新增一条记录，并将上次获取积分的日期改为今天
                    iRewardService.updateRewards(signintemplateEntity.getTid(), 0, 0, 0, 1, currentDay, rewardPoints + rewardPerTime, rewardPerTime);
                } else {
                    //如果上次获取积分的日期等于今天

//                    if(dayMaxReward<rewards.getDay_reward()) {
                    if (dayMaxReward < rewardPointsEntity.getDayReward()) {
                        code = 2;
                    }
                    //判断是不是今天第一次获取
                    else if (limitFromRecordActivity == 0) {
                        iRewardService.updateRewards(signintemplateEntity.getTid(), limitFromRecordA, limitFromRecordB, limitFromRecordC, 1, currentDay, rewardPoints + rewardPerTime, rewardPointsEntity.getDayReward() + rewardPerTime);
                    } else {
                        code = 3;
                    }
                }
            }
            //提交事务
            platformTransactionManager.commit(status);
            return code;

        } catch (Exception e) {

            //回滚事务
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return 0;
        }
    }


    @Override
    public Integer createActivity2(int templateId, TemplateInfoAmend templateInfoAmend) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        int code = 1;
        try {

            String actId = GetInfoUtil.getId();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = dateFormat.format(System.currentTimeMillis());

            //创建签到活动
            SigninactivityEntity signinactivityEntity = new SigninactivityEntity();
            signinactivityEntity.setActid(actId)
                    .setTitle(templateInfoAmend.getTitle())
                    .setCreatetime(currentTime)
                    .setCaption(templateInfoAmend.getCaption())
                    .setActtype(templateInfoAmend.getActType())
                    .setSignStopType(templateInfoAmend.getSignStopType())
                    .setCid(templateInfoAmend.getCid())
                    .setTid(templateInfoAmend.getTid());
            signinactivityMapper.insert(signinactivityEntity);

            //创建此签到活动下的所有衍生签到（link）
            String[] types = templateInfoAmend.getLinkType().split(",");
            String[] times = templateInfoAmend.getTimes().split(",");
            String[] durations = templateInfoAmend.getDuration().split(",");
            String[] locations = templateInfoAmend.getWhetherLocation().split(",");

            for (int i = 0; i < types.length; i++) {
                for (int j = 0; j < Integer.parseInt(times[i]); j++) {

                    SigninlinkEntity signinlinkEntity = new SigninlinkEntity();
                    signinlinkEntity.setLid(GetInfoUtil.getId())
                            .setLinktype(Integer.parseInt(types[i]))
//                            .setStarttime()
//                            .setEndtime()
                            .setDuration(durations[i])
                            .setStatus(0)
                            .setActid(signinactivityEntity.getActid());
                    if (Integer.parseInt(locations[i]) == 0)
                        signinlinkEntity.setLocationX(0.0)
                                .setLocationY(0.0)
                                .setRangement(0.0);

                    //手动开闭签到
                    if(templateInfoAmend.getSignStopType() == 1){
                        signinlinkEntity.setStatus(1)
                                .setDuration("∞");
                        signinlinkMapper.insert(signinlinkEntity);

                        //同时生成签到码
                        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                        StringBuilder randomCode = new StringBuilder();
                        for(int k=0;k<6;k++)
                        {
                            char c = str.charAt(new Random().nextInt(str.length()));
                            randomCode.append(c);
                        }
                        redisTemplate.opsForValue().set(signinlinkEntity.getLid() + "-code", randomCode.toString());
                    }else
                        signinlinkMapper.insert(signinlinkEntity);
                }
            }

            //模板使用次数+1
            SignintemplateEntity signintemplateEntity = signintemplateMapper.selectById(templateId);
            if (signintemplateEntity.getUseNum() == null)
                signintemplateEntity.setUseNum(1);
            else
                templateInfoAmend.setUseNum(signintemplateEntity.getUseNum() + 1);
            signintemplateMapper.updateById(signintemplateEntity);

            //创建关联
            TemplateActivityLinkEntity templateActivityLinkEntity = new TemplateActivityLinkEntity();
            templateActivityLinkEntity.setActivityId(actId)
                    .setTemplateId(templateId);
            templateActivityLinkMapper.insert(templateActivityLinkEntity);

            //判定积分情况
            final int rewardPerTime = 30;
            final int dayMaxReward = 100;
            RewardPointsEntity rewardPointsEntity = rewardPointsMapper.selectOne(new QueryWrapper<RewardPointsEntity>().eq("uid", templateInfoAmend.getTid()));
            String lastGainDay;
            String currentDay = dateFormat.format(System.currentTimeMillis()).substring(0, 10);
            //先判断列表是否有记录，没有则新增记录

            if (rewardPointsEntity == null) {
                iRewardService.addNewRewards(templateInfoAmend.getTid(), 0, 0, 0, 1,
                        currentDay, rewardPerTime, rewardPerTime);
            } else {
                //有则更新记录
                int limitFromRecordA = rewardPointsEntity.getLimitFromRecordA();
                int limitFromRecordB = rewardPointsEntity.getLimitFromRecordB();
                int limitFromRecordC = rewardPointsEntity.getLimitFromRecordC();
                int limitFromRecordActivity = rewardPointsEntity.getLimitFromActivity();
                lastGainDay = rewardPointsEntity.getLastGainDay();
                int rewardPoints = rewardPointsEntity.getRewardPoints();
                log.info("lastGainDay:" + lastGainDay);

                if (!lastGainDay.equals(currentDay)) {
                    //如果上次获取积分的日期不等于今天，则直接新增一条记录，并将上次获取积分的日期改为今天
                    iRewardService.updateRewards(templateInfoAmend.getTid(), 0, 0, 0, 1, currentDay, rewardPoints + rewardPerTime, rewardPerTime);
                } else {
                    //如果上次获取积分的日期等于今天

//                    if(dayMaxReward<rewards.getDay_reward()) {
                    if (dayMaxReward < rewardPointsEntity.getDayReward()) {
                        code = 2;
                    }
                    //判断是不是今天第一次获取
                    else if (limitFromRecordActivity == 0) {
                        iRewardService.updateRewards(templateInfoAmend.getTid(), limitFromRecordA, limitFromRecordB, limitFromRecordC, 1, currentDay, rewardPoints + rewardPerTime, rewardPointsEntity.getDayReward() + rewardPerTime);
                    } else {
                        code = 3;
                    }
                }
            }
            //提交事务
            platformTransactionManager.commit(status);
            return code;

        } catch (Exception e) {

            e.printStackTrace();
            //回滚事务
            platformTransactionManager.rollback(status);
            return 0;
        }
    }


}
